import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Login from '@/views/login/index.vue'
import { ApiUserInfo } from '@/http/api/index'
import { useUserStore } from '@/store/user'
import Home from '@/views/home/index.vue'
import { ElMessage } from 'element-plus'
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: Home,
    redirect: 'index',
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('@/views/index/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
]

const router = createRouter({
  routes,
  history: createWebHashHistory(),
})

// 添加前置路由全局守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const store = useUserStore()
  if (!token && to.name !== 'login') {
    ElMessage.error("请先登录！");
    next('login')

    // 阻止未登录跳转登录页
  } else if (token && to.name === 'login' && store.menus.length !== 0) {
    ElMessage.warning("请先退出登录！");
    next(from.fullPath)
  } else {
    if (store.menus.length == 0 && token) {
      // 发请求请
      ApiUserInfo().then((res) => {
        if (res.code === 200) {
          store.menus = res.data.menus
          store.username = res.data.username
          // 添加动态路由
          store.routerMenu.forEach((item) => {

            const route: RouteRecordRaw = {
              path: '/' + item.name,
              name: item.name,
              component: () => import('@/views/home/index.vue'),
              meta: {
                title: item.title
              },
              // redirect: '',
              children: item.children.map((sub) => ({
                path: sub.name,
                name: sub.name,
                component: () => import(`@/views/${item.name}/${sub.name}.vue`),
                meta: {
                  title: sub.title
                },
              })),
            }

            if (item.children[0]) {
              // 访问一级路由，默认跳转第一个子路由
              route.redirect = `/${item.name}/${item.children[0].name}`
            }

            router.addRoute(route)
          })
        }
        // 要在路由添加进来之后重新跳转到一个指定的路由
        next(to.fullPath)
      })
    } else {
      next()
    }
  }
})
export default router
